<!-- 商品类型列表 -->
<template>
    <div class="container">
        <!-- 搜索框独立行 -->
        <div class="search-container">
            <el-input v-model="search" size="small" placeholder="请输入商品类型名称搜索" style="width: 200px;" clearable>
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="showAddGoodTypeDialog" style="margin-left: 16px;">
                添加新商品类型
            </el-button>
        </div>

        <!-- 表格另起一行 -->
        <el-scrollbar>
            <el-table :data="filterTableData" style="width: 100%" @row-click="handleRowClick" height="700">
                <el-table-column prop="typeId" label="商品类型ID" show-overflow-tooltip>
                    <template #default="{ row }">

                        <span>{{ row.typeId }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="typeName" label="商品类型名称" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-input v-if="row.isEdit && row.isDelete == '0'" v-model="row.typeName"
                            size="small"></el-input>
                        <span v-else>{{ row.typeName }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="inventory" label="库存" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-input-number v-if="row.isEdit && row.isDelete == '0'" v-model="row.inventory"
                            :min="row.inventory" :controls="true" :step="1" size="small"
                            @change="handleInventoryChange"></el-input-number>
                        <span v-else>{{ row.inventory }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="isDelete" label="是否删除" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-select v-if="row.isEdit" v-model="row.isDelete" size="small">
                            <el-option :label="'不删除'" :value="0"></el-option>
                            <el-option :label="'删除'" :value="1"></el-option>
                        </el-select>
                        <span v-else>{{ row.isDelete === 0 ? '不删除' : '删除' }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                        <el-button v-if="!row.isEdit" type="primary" @click="editRow(row)">修改</el-button>
                        <el-button v-else type="success" @click="saveRow(row)">保存</el-button>
                        <el-button v-if="row.isEdit" @click="cancelEdit(row)">取消</el-button>
                        <el-button v-if="!row.isEdit" type="danger" @click="deleteRow(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
            <!-- 添加分页组件 -->
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[6, 12, 24, 48]"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes, prev, pager, next"
                class="pagination"
            />
        </el-scrollbar>
        <AddGoodType ref="addGoodTypeRef" @refresh-list="refreshList"></AddGoodType>
    </div>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { Search } from '@element-plus/icons-vue'
import axios from "axios";
import { ElMessage, ElMessageBox } from 'element-plus'
import AddGoodType from './AddGoodType.vue'

const goodTypes = ref([]);
const originalGoodTypes = ref([]);

const editRow = (row) => {
    row.isEdit = true;
};

const cancelEdit = (row) => {
    const index = goodTypes.value.indexOf(row);
    if (index !== -1) {
        if (row.isNew) {
            goodTypes.value.splice(index, 1);
        } else {
            const originalRow = originalGoodTypes.value[index];
            goodTypes.value[index] = { ...originalRow, isEdit: false };
        }
    }
};
const deleteRow = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除这个商品类型吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        const response = await axios.post('/deleteGoodType',
            row.typeId,
            {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: sessionStorage.getItem('Authorization')
                }
            }
        )
        if (response.data.status === 200) {
            ElMessage.success(response.data.message);
            goodTypes.value = goodTypes.value.filter(goodType => goodType.typeId !== row.typeId);
        } else {
            ElMessage.error(response.data.message);
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            })
        } else {
            ElMessage.error('删除失败');
        }
    }
};

const saveRow = (row) => {
    const payload = {
        typeId: row.typeId,
        typeName: row.typeName,
        inventory: row.inventory,
        isDelete: Number(row.isDelete),
    };

    axios
        .post("/updateGoodType", payload, {
            headers: {
                Authorization: sessionStorage.getItem("Authorization"),
            },

        })
        .then((response) => {

            row.isEdit = false;
            const index = goodTypes.value.indexOf(row);
            if (index !== -1) {
                originalGoodTypes.value[index] = { ...row };
            }
            if (response.data.status === 200 || response.data.status === 500) {
                ElMessage.success('保存成功');
                row.isEdit = false;
                row.avatarFile = null; // 清除临时文件

            }
            else {
                ElMessage.error('保存失败');
            }
        })

        .catch((error) => {
            ElMessage.error(error.message);
        });
};

const refreshList = async () => {
    try {
        const response = await axios.get("/good_type", {
            params: {
                current: currentPage.value,
                size: pageSize.value
            },
            headers: {
                Authorization: sessionStorage.getItem("Authorization"),
            },
        });
        goodTypes.value = response.data.data.records.map((type) => ({
            ...type,
            isDelete: Number(type.isDelete),
            isEdit: false,
        }));
        total.value = response.data.data.total;
        originalGoodTypes.value = response.data.data.records.map((type) => ({
            ...type,
            isDelete: Number(type.isDelete)
        }));
    } catch (error) {
        ElMessage.error(error.message);
    }
};

onMounted(() => {
    refreshList()
});

const search = ref("");
const filterTableData = computed(() =>
    goodTypes.value.filter(
        (type) =>
            !search.value ||
            type.typeName.toLowerCase().includes(search.value.toLowerCase())
    )
);

const handleInventoryChange = (value, row) => {
    if (value < row.inventory) {
        const originalInventory = row.inventory;
        row.inventory = originalInventory;
        ElMessage.warning('库存只能增加，不能减少');
    }
}
const addGoodTypeRef = ref(null)
const showAddGoodTypeDialog = () => {
    addGoodTypeRef.value.dialogVisible = true
}

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)

// 处理页码改变
const handleCurrentChange = (val) => {
    currentPage.value = val;
    refreshList();
}

// 处理每页显示数量改变
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1; // 重置为第一页
    refreshList();
}
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.search-container {
    width: 100%;
    padding: 20px;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
}

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 添加分页组件的样式 */
.pagination {
    display: flex;
    justify-content: center;  /* 水平居中 */
    align-items: center;      /* 垂直居中 */
}
</style>